<?

/*	Admin page and handling */

	// include config, languages file and system functions
	require_once("config.php");
	$blogRoot="../".$blogRoot;
	
	
	require_once($blogRoot."functions.php");
	require_once($blogRoot."admin-functions.php");

	$usertheme=$theme;
	$theme="_system";



	//$msg=Messages("",$lang,$msg,$err);
	$action=Actions();



	/* link the theme functions */
	require_once($blogRoot."themes/".$theme."/functions.php");
	require_once($blogRoot."themes/_system/pageheader.php");
	
	/* link in the theme-header */
	require_once($blogRoot."themes/".$theme."/header.php");

	$page="";
	if (isset($_GET['page'])) $page=$_GET['page'];

			/* render our page header*/
?>			
			<div id='profile'>
				<img src='<?=$blogRoot."themes/_system/imgs/logo.png";?>' style='border:0px;'>
				<h1>Admin</h1>
			</div>

		
			
			<div id="post">

<?

			/* not logged in, show login screen */
			if (!$loggedIn) {
					print "<div>";
					print "<a href='".$blogRoot."../?'>Visit blog</a>";
					print "</div><br/>";

			
					print '<div class="actions center">
									<form action="#" method="post">
										'.$lang["form_password"].': <input type="password" name="password" size="10"> 
										<input style="width:16px;" type="checkbox" name="permanent" value="1"><small>Permanent</small>&nbsp;&nbsp;<input type="submit" name="submit" value="'.$lang["menu_login"].'">
									</form>
								</div>';
								
			}



			if ($loggedIn) {

				switch ($page) {
				
						default: 
							// actions
							print "<div>";
							print "<a href='".$blogRoot."../?'>Visit blog</a>";
							
							if ($install_completed) {
								print " | <a href='?page=services'>Services</a>";		
								print " | <a href='?page=puddle'>New post</a>";
							}
							
							print "</div><br/>";						
						
						
							// optionally display more information here
							?>
							<h1 class='syscaption'>// dashboard</h1>
							<?
							
							clearstatcache();
							
							// are the required directories available?
							print "<div id='actioncontainer'>";
							
							if (!file_exists($blogRoot."settings")) {
								if (!mkdir($blogRoot."settings",0777)) {
									print "Problem creating settings/ directory...:(<br/>";
									print "Make sure you have given write-permission to the puddle/ directory.";
								} else {
									print "created settings/ directory...:)<br/>";
								}
							}

							// create txts directory
							if (!file_exists($blogRoot."txts")) {
								if (!mkdir($blogRoot."txts",0777)) {
									print "Problem creating txts/ directory...:( <br/>";
									print "Make sure you have given write-permission to the puddle/ directory.";
								} else {
									print "created txts/ directory...:)<br/>";
								}
							}
							
							
							// Config file not existing? then we create a new one
							if (file_exists($blogRoot."settings") && !file_exists($blogRoot."settings/config.txt")) {
								writeConfigSetting("blogtitle","Puddle blog");
								writeConfigSetting("blogname","My Puddle");
								writeConfigSetting("maxpostsperpage",25);
								
								writeConfigSetting("showmenu","1");
								writeConfigSetting("enableComments","0");	// only possible if there is a disqus linked in
								
								writeConfigSetting("includeATtweets","0");
								writeConfigSetting("theme","puddlelight");
								readFullConfig();

								print 
									"<p>Welcome to your own Puddle blog<br/>
									it seems this is the first time you are logging into the system, so we will have to 
									do a little setup first.</p>
									<p>A general config was created, so you will probably want to change the settings
									of your blog first.</p>
									<p>Click on 'Puddle settings' on the right to change the preferences.</p>
								";
							}

							print "</div>";
							
							if ($install_completed) {
								if ($password==md5("puddle")) {
									print "
										<p>You are using the default password on your Puddle blog.
										It's best to change that password now:</p>
										<form action='#' method='post'>
											<input type='password' name='npassword'> 
											<input type='submit' name='savenpass' value='save'>
										</form>
										";
								}
							
							
							// show some stats
								print "Puddle:<a href='".$blogRoot."../'>".$blogtitle."</a> owned by <a href='?page=general'>".$blogname."</a><br/>";
								// count amounts of posts
									print " - ".countTweets()." posts.<br/>";
									
								// count amount of services
									print " - ".count($pluginServices)." service plugins installed.<br/>";
								
								// count normal plugins
									print " - ".count($plugins)." system plugins installed.<br/>";
									
								archiveTweets();
							} else {
								print "<a href='".$blogRoot."admin.php'>refresh page</a>";
							}
							
							
							
							?>
							<p><br/></p>
							<h1 class='syscaption'>// release info</h1>
							
							<p>First initial release of Puddle. Still many things that probably need fixing and improving 
							but I just wanted to get this code out there to see if there is interest in it. 
							So here it is!</p>
							
							<p>Some of the "todo" things</p>
							<ul>
								<li>Post-editing isn't working yet</li>
								<li>cronjob for auto-refreshing isn't working correctly (not at all?)</li>
								<li>DIGG feeds give error? what's up with that Digg!?</li>
								<li>Picassa is a pain in the behind, probably need to use API code for this</li>
								<li>Multi-language support</li>
							</ul>
							
							
							<?
							
						break;
						
						
						
						
						// General settings, like blogtitle, user info, etc
						case "general":
							// actions
							print "<div>";
							//print "<a href='".$blogRoot."../?'>Visit blog</a>";
							//print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
							print "</div><br/>";
							
							// save / update main settings?
							if (isset($_POST['savemainsettings'])) {
								writeConfigSetting("blogtitle",$_POST['blogtitle']);
								writeConfigSetting("blogname",$_POST['blogname']);
								writeConfigSetting("disqusname",$_POST['disqusname']);
								writeConfigSetting("profileimg",$_POST['profileimg']);
								
								if ($_POST['newpassword']!='newpassword') writeConfigSetting("password",md5($_POST['newpassword']));
								readFullConfig();
								
								print "<div id='actioncontainer'>settings saved... :)</div>";
							}	
							
							
							?>
							<h1 class='syscaption'>// puddle settings</h1>
							
							<form action="#" method="post">

								<table>
									<tr>
										<td valign=top>Password:</td>
										<td>
											<input type='password' name='newpassword' size='45' value='newpassword'><br/>
											only if you want to change it
										</td>
									</tr>

									<tr>
										<td colspan=2>&nbsp;</td>
									</td>

									<tr>
										<td>Owner name:</td>
										<td><input type='text' name='blogname' size='45' value='<?=htmlspecialchars($blogname,ENT_QUOTES);?>'></td>
									</tr>
									
									<tr>
										<td>Blog Title:</td>
										<td><input type='text' name='blogtitle' size='45' value='<?=htmlspecialchars($blogtitle,ENT_QUOTES);?>'></td>
									</tr>
									

									<tr>
										<td>Disqus forum name:</td>
										<td><input type='text' name='disqusname' size='45' value='<?=htmlspecialchars($disqusname,ENT_QUOTES);?>'></td>
									</tr>
									<tr>
										<td>&nbsp;</td>
										<td>The name of your <a href='http://disqus.com'>disqus forum</a><br/>
										You can create a free account there and use it for comments<br/>
										on your Puddle blog
										</td>
									</tr>

									
									<tr>
										<td>Profile image URL:</td>
										<td><input type='text' name='profileimg' size='45' value='<?=htmlspecialchars($profileimg,ENT_QUOTES);?>'></td>
									</tr>

									
									<tr>
										<td></td>
										<td><input type='submit' name='savemainsettings' value='Save'></td>
									</tr>
								</table>
								
								
							</form>
							<?
						break;
						
						
						
						case "appearance":
							// actions
							print "<div>";
							//print "<a href='".$blogRoot."../?'>Visit blog</a>";
							//print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
							print "</div><br/>";
							
							// save / update main settings?
							if (isset($_POST['saveappsettings'])) {
								writeConfigSetting("theme",$_POST['theme']);
								writeConfigSetting("maxpostsperpage",$_POST['maxpostsperpage']);
								
								readFullConfig();
								$usertheme=$theme;
								$theme="_system";
								
								print "<div id='actioncontainer'>settings saved... :)</div>";
							}	
							
							
							?>
							<h1 class='syscaption'>// appearance settings</h1>
							
							<form action="#" method="post">

								<table>
									<tr>
										<td>Puddle theme:</td>
										<td>
											<select name='theme'>
											<?
												// fetch all available themes
												$handle=opendir($blogRoot."themes/"); 
												$retVal=null;
												$pluginServices=array();
												while ($file = readdir($handle)) { 
													if (substr($file,0,1)!="." && substr($file,0,1)!="_") {
														print "<option value='".$file."'";
														if ($file==$usertheme) print " SELECTED";
														print ">".$file."</a>";
													}
												} 
											?>
											</select>
										</td>
									</tr>
									
									<tr>
										<td colspan=2>&nbsp;</td>
									</td>

									<tr>
										<td>Posts per page:</td>
										<td><input type='text' name='maxpostsperpage' size='3' value='<?=$maxpostsperpage;?>'></td>
									</td>

									
									<tr>
										<td></td>
										<td><input type='submit' name='saveappsettings' value='Save'></td>
									</tr>
								</table>
								
								
							</form>
							<?
						break;
						
						
						case "services":
							// actions
							print "<div>";
							//print "<a href='".$blogRoot."../?'>Visit blog</a>";
							//print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
							print "<a href='#' onClick='addService(0); return false;'>Add service</a>";		
							print " | <a href='#' onClick='updService(0); return false;'>Refresh services</a>";		
							print "</div><br/>";

							if (isset($_POST['addservice'])) addService();
?>

							<div id="actioncontainer" style='display:none;'>
							</div>

							<script>
								closeButton="<span class='closeme'><a href='#' onClick='closeContainer(); return false'>X</a></span>";
								
								function closeContainer() {
									document.getElementById('actioncontainer').style.display='none';
								}
								
								function addService(serviceID) {
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?addService='+serviceID,true);
									xmlHttp.send(null);									
								}			
								

								/* update specified service */
								
								function updService(serviceID) {
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?updService='+serviceID,true);
									xmlHttp.send(null);									
								}			



								/* delete specified service */
								
								function delService(serviceID) {
									
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									var answer = confirm ("Also remove imported entries?");

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
											// also remove the service from view 
											document.getElementById('service'+serviceID).style.display='none';
											document.getElementById('serviceIcon'+serviceID).style.display='none';
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?delService='+serviceID+'&delentries='+answer,true);
									xmlHttp.send(null);									
								}			
							</script>

							<h1 class='syscaption'>// linked services</h1>
<?
							fetchServices();
						break;


						case "sidebar":
							// actions
							print "<div>";
							//print "<a href='".$blogRoot."../?'>Visit blog</a>";
							//print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
							print "<a href='#' onClick='addPlugin(0); return false;'>Add plugin</a>";		
							print "</div><br/>";

							if (isset($_POST['addPlugin'])) addPlugin("sidebar");
							if (isset($_POST['updPlugin'])) addPlugin("sidebar",true);	// update existing one

							include $blogRoot."scripts/dragdrop.js";
	
?>
							<div id="actioncontainer" style='display:none;'>
							</div>
							
							

							<script>
								closeButton="<span class='closeme'><a href='#' onClick='closeContainer(); return false'>X</a></span>";
								
								function closeContainer() {
									document.getElementById('actioncontainer').style.display='none';
								}
								
								function addPlugin(serviceID) {
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?addPlugin='+serviceID,true);
									xmlHttp.send(null);									
								}			
								

								/* update specified service */
								
								function updPlugin(serviceID) {

									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?updPlugin='+serviceID+'&st=sidebar',true);
									xmlHttp.send(null);									
								}			



								/* delete specified service */
								
								function delPlugin(serviceID) {
									
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').innerHTML=closeButton;
											document.getElementById('actioncontainer').innerHTML+=content;
											// also remove the service from view 
											document.getElementById('service'+serviceID).style.display='none';
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?delPlugin='+serviceID+'&st=sidebar',true);
									xmlHttp.send(null);									
								}			
								
								
								/* Sort plugins */
								
								function sortPlugin() {
									sortorder=saveArrangableNodes();	// sort according to drag/dropping from user
									
									document.getElementById('actioncontainer').style.display='';
									document.getElementById('actioncontainer').innerHTML=closeButton;
									myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											document.getElementById('actioncontainer').style.display='none';
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?sortPlugins='+sortorder,true);
									xmlHttp.send(null);									
								}
							</script>

							<h1 class='syscaption'>// sidebar plugins</h1>
							<p>Drag and drop the plugins in the order you want, and then click Save</p>
							<br/><br/>
							
<?
							
							// read list of active plugins in the sidebar
							fetchSidebarPlugins();
							
						break;


						// General settings, like blogtitle, user info, etc
						case "puddle":
							if($_POST["submit"]=="Publish") {
								addTweet();
								print "<div>";
								print "<a href='".$blogRoot."../?'>Visit blog</a>";
								print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
								print "</div><br/>";
								print "<h1>Done!</h1>";
								print "<p>Your post was saved.. </p>";
							} else {
							
									// actions
									print "<div>";
									//print "<a href='".$blogRoot."../?'>Visit blog</a>";
									//print " | <a href='".$blogRoot."admin.php'>Admin main</a>";
									print "</div><br/>";
									
									
									if (isset($_GET['edit'])) {
										print "<h1 class='syscaption'>// edit post</h1>";
										$caption="";
										$message="";
										$tweetID=$_GET['edit'];
										
										// fetch the entry
										$itemdate=date("YmdHis",$tweetID);
										
										$myfile=$blogRoot."txts/".date("Y",$tweetID).".".date("m",$tweetID).".txt";
										
										clearstatcache();
										if((file_exists($myfile)) && filesize($myfile)!="0") {
												
												// load archive
												$load = @file($myfile);

												// load lines
												while(count($load)) {
													$line=array_shift($load);
													$info=explode("|",$line);
													if (date("YmdHis",strtotime($info[0]))==$itemdate) {
													
														// retrieve correct caption and message
														if (function_exists($info[2]."_getCaption")) $caption=call_user_func($info[2]."_getCaption",$line);
														else $caption=$info[3];

														if (function_exists($info[2]."_getPost")) $message=call_user_func($info[2]."_getPost",$line);
														else $message=$info[5];
													}
												}
										}								
									} else {
										$caption=$_POST['caption'];
										$message=$_POST['message'];
										print "<h1 class='syscaption'>// add new post</h1>";	
									}
									
									
									// entry form
									print "<script type='text/javascript' src='".$blogRoot."scripts/tiny_mce/tiny_mce.js'></script>";
		?>

										<script type="text/javascript">
											tinyMCE.init({
												mode: "textareas",
												theme: "advanced",
												theme_advanced_toolbar_location: "top",
												theme_advanced_toolbar_align: "left",
												theme_advanced_buttons2 : "",
												theme_advanced_buttons3: "",
												remove_linebreaks: true,
												plugins : "inlinepopups",
												dialog_type : "modal",
												theme_advanced_buttons1_add: "bullist,numlist,blockquote,image,link,unlink,code  ",
												theme_advanced_disable: "formatselect, fontselect, fontsizeselect, styleselect, justifyfull  "
											});
									</script>
		<?							
									print "<form action='#' method='post'>";
									if ($tweetID) print "<input type='hidden' name='id' value='".$tweetID."'>";
									
									print "<p><input name='caption' value='".$caption."' size='100'></p>
										
											<textarea id='elm1' name='message' maxlength='150' rows='20'>".$message."</textarea>
											
											<br/>
											<span style='float:right;'>
											<input type='submit' name='submit' value='Publish'>
											</span>
										</form>
									";
								}
						break;


						// Manage posts (edit, hide/unhide, etc)
						case "posts":
?>
							<script>
								function closeContainer() {
									document.getElementById('actioncontainer').style.display='none';
								}
								
								function hideTweet(tweetID) {
									//document.getElementById('actioncontainer').style.display='';
									//myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											//document.getElementById('actioncontainer').innerHTML=content;
											document.getElementById("show"+tweetID).style.display=''; 
											document.getElementById("hide"+tweetID).style.display='none'; 
											document.getElementById("tweet"+tweetID).className='hidden';
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?hideTweet='+tweetID,true);
									xmlHttp.send(null);									
								}


								function showTweet(tweetID) {
									//document.getElementById('actioncontainer').style.display='';
									//myThrobberOn('actioncontainer');

									xmlHttp=ajaxFunction();
									xmlHttp.onreadystatechange=function() {
										if(xmlHttp.readyState==4) {
											content=xmlHttp.responseText;
											//document.getElementById('actioncontainer').innerHTML=content;
											document.getElementById("hide"+tweetID).style.display=''; 
											document.getElementById("show"+tweetID).style.display='none'; 
											document.getElementById("tweet"+tweetID).className='';
										}
									}

									xmlHttp.open('GET','<?=$blogRoot;?>ajax-functions.php?showTweet='+tweetID,true);
									xmlHttp.send(null);									
								}
							</script>

<?						
									print "<div>";
										print "<a href='?page=posts'>posts</a>";
										print " | <a href='?page=posts&hid=1'>hidden posts</a>";
										print " | <a href='?page=puddle'>New post</a>";									
									print "</div><br/>";
?>
									<!--<div id="actioncontainer" style='display:none;'>
									</div>-->
<?
									
									
									print "<h1 class='syscaption'>// posts</h1>";
									
									print "<table class='listview'>";
										print "<thead><tr><th>Post</th><th>Service</th><th>Date</th></tr></thead>";
										print "<tfoot><tr><th>Post</th><th>Service</th><th>Date</th></tr></tfoot>";
										print "<tbody>";

										if (isset($_GET["idx"])) $page=$_GET["idx"];
										else $page=1;
										
										if (isset($_GET['hid'])) $hidden=true;
										else $hidden=false;

										print loadPosts($page,$hidden);
										
										print "</tbody>";
									
									print "</table>";
						
						break;


					}// end $page==''
					
			}// end loggedIn stuff
?>
			</div>
		</div>
		
		<div id="sidebar">
		<?
			if ($install_completed)  {
		?>
			<h2>Options</h2>
				<a id='tabMenu' href='<?=$blogRoot;?>../?'>Visit Blog</a>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?'>Dashboard</a>
				
			<h2>content</h2>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?page=posts'>Posts</a>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?page=services'>Services</a>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?page=sidebar'>Sidebar</a>
				
			<h2>settings</h2>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?page=general'>Puddle settings</a>
				<a id='tabMenu' href='<?=$blogRoot;?>admin.php?page=appearance'>Appearance</a>
		<?
			} else {
		?>
			<h2>Information</h2>
				<p>You are almost ready to use Puddle.</p>
				<p>Please see the instructions on the left to complete your install of Puddle.</p>
		<?
			}
		?>
		
		</div>
<?
			
			print "<div style='clear:both;'> </div>";

			require_once($blogRoot."themes/_system/footer.php");		
			require_once($blogRoot."themes/_system/pagefooter.php");		
?>

